import cors from 'cors';
import express, { Response } from 'express';
import { Server } from 'socket.io';

import { auth } from './src/auth/verify';
import { connectWs } from './src/config/ws';
import router from './src/modules/router/router';
import mock from './src/modules/mock/mock';
import { createSerialPort, parser } from './src/config/serialport';

const app = express();
const expressServer = app.listen(20000);

createSerialPort();

app.use(express.json());

app.use(express.urlencoded({ extended: true }));

const corsOptions = {
  allowedHeaders: ['Authorization', 'Content-Type'],
  charset: 'utf-8',
};

app.use(cors(corsOptions));

app.use(auth);

/* 路由 */
app.use('/', router);
app.use('/mock', mock);

app.use((err, req, res: Response, next) => {
  res.status(500).send({
    code: 500,
    message: 'Internal Server Error',
    data: null,
  });
});

const io = new Server(expressServer, {
  cors: {
    origin: '*',
  },
});
connectWs(io);
